package com.seven.netty.protocol.handler;

import com.seven.netty.protocol.bean.Message;
import com.seven.netty.protocol.enums.MessageTypeEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author chendongdong
 * @description TODO
 * @since 2024/3/6 11:27
 */
@Slf4j
@Component
public class MessageHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        if (msg != null && message.getHead().getMessageType().equals(MessageTypeEnum.HANDSHAKE_REQUEST.getType().byteValue())) {
            Channel channel = ctx.channel();
            String ip = channel.remoteAddress().toString();
            InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
            log.info("message hand shake request address:{},remoteIp:{},message:{}", address.toString(), ip,message);

            message.getHead().setMessageType(MessageTypeEnum.HEARTBEAT_RESPONSE.getType().byteValue());
            ctx.writeAndFlush(message);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("message handler caught:", cause);
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
            log.debug("message handler caught ,channel close");
        }
    }
}
